package com.studentmanagement.ui;

import com.studentmanagement.model.Course;
import com.studentmanagement.model.Enrollment;
import com.studentmanagement.model.User;
import com.studentmanagement.service.CourseService;
import com.studentmanagement.service.EnrollmentService;
import com.studentmanagement.service.StudentService;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;

public class MyGradePanel extends JPanel {
    private User currentUser;
    private CourseService courseService;
    private EnrollmentService enrollmentService;
    private StudentService studentService;
    
    private JTable gradeTable;
    private DefaultTableModel tableModel;
    private JComboBox<String> semesterComboBox;
    private JLabel gpaLabel;
    private JButton refreshButton;
    private JButton exportButton;

    public MyGradePanel(User user) {
        this.currentUser = user;
        this.courseService = new CourseService();
        this.enrollmentService = new EnrollmentService();
        this.studentService = new StudentService();
        
        initComponents();
        setupLayout();
        setupListeners();
        loadGradeData();
    }

    private void initComponents() {
        // 表格列名
        String[] columnNames = {"课程代码", "课程名称", "教师", "学分", "成绩", "绩点", "学期"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        
        gradeTable = new JTable(tableModel);
        gradeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        gradeTable.getTableHeader().setReorderingAllowed(false);
        gradeTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        gradeTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        gradeTable.setRowHeight(30);
        
        // 学期选择下拉框
        semesterComboBox = new JComboBox<>(new String[]{"全部", "2023-2024-1", "2023-2024-2"});
        
        // GPA标签
        gpaLabel = new JLabel("平均绩点：0.00");
        
        // 按钮初始化
        refreshButton = new JButton("刷新");
        exportButton = new JButton("导出成绩单");
        
        // 设置字体
        Font font = new Font("微软雅黑", Font.PLAIN, 14);
        semesterComboBox.setFont(font);
        gpaLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        refreshButton.setFont(font);
        exportButton.setFont(font);
    }

    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 创建标题面板
        JPanel titlePanel = new JPanel();
        JLabel titleLabel = new JLabel("我的成绩");
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titlePanel.add(titleLabel);

        // 创建筛选面板
        JPanel filterPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        filterPanel.add(new JLabel("学期:"));
        filterPanel.add(semesterComboBox);
        filterPanel.add(Box.createHorizontalStrut(20));
        filterPanel.add(gpaLabel);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        buttonPanel.add(exportButton);
        buttonPanel.add(refreshButton);

        // 创建北部面板，包含标题、筛选和按钮
        JPanel northPanel = new JPanel(new BorderLayout());
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(titlePanel, BorderLayout.WEST);
        topPanel.add(buttonPanel, BorderLayout.EAST);
        northPanel.add(topPanel, BorderLayout.NORTH);
        northPanel.add(filterPanel, BorderLayout.CENTER);

        // 添加组件到主面板
        add(northPanel, BorderLayout.NORTH);
        add(new JScrollPane(gradeTable), BorderLayout.CENTER);
    }

    private void setupListeners() {
        semesterComboBox.addActionListener(e -> loadGradeData());
        refreshButton.addActionListener(e -> loadGradeData());
        exportButton.addActionListener(e -> exportGrades());
    }

    private void loadGradeData() {
        tableModel.setRowCount(0);
        String selectedSemester = (String) semesterComboBox.getSelectedItem();
        
        List<Enrollment> enrollments = enrollmentService.getEnrollmentsByStudentId(
            studentService.getStudentByUserId(currentUser.getId()).getId()
        );
        
        double totalGradePoints = 0;
        double totalCredits = 0;
        
        for (Enrollment enrollment : enrollments) {
            Course course = courseService.getCourseById(enrollment.getCourseId());
            
            // 如果选择了特定学期且不匹配，则跳过
            if (!"全部".equals(selectedSemester) && !selectedSemester.equals(course.getSemester())) {
                continue;
            }
            
            // 只显示有成绩的课程
            if (enrollment.getGrade() != null) {
                double gradePoint = calculateGradePoint(enrollment.getGrade());
                double credits = course.getCredits();
                
                Object[] rowData = {
                    course.getCourseCode(),
                    course.getName(),
                    course.getTeacherName() != null ? course.getTeacherName() : "未分配",
                    credits,
                    enrollment.getGrade(),
                    String.format("%.2f", gradePoint),
                    course.getSemester()
                };
                tableModel.addRow(rowData);
                
                totalGradePoints += gradePoint * credits;
                totalCredits += credits;
            }
        }
        
        // 更新GPA显示
        double gpa = totalCredits > 0 ? totalGradePoints / totalCredits : 0;
        gpaLabel.setText(String.format("平均绩点：%.2f", gpa));
    }

    private double calculateGradePoint(String grade) {
        try {
            double numericGrade = Double.parseDouble(grade);
            if (numericGrade >= 90) return 4.0;
            if (numericGrade >= 85) return 3.7;
            if (numericGrade >= 82) return 3.3;
            if (numericGrade >= 78) return 3.0;
            if (numericGrade >= 75) return 2.7;
            if (numericGrade >= 72) return 2.3;
            if (numericGrade >= 68) return 2.0;
            if (numericGrade >= 64) return 1.5;
            if (numericGrade >= 60) return 1.0;
            return 0.0;
        } catch (NumberFormatException e) {
            // 处理非数字成绩
            switch (grade.toUpperCase()) {
                case "A": return 4.0;
                case "A-": return 3.7;
                case "B+": return 3.3;
                case "B": return 3.0;
                case "B-": return 2.7;
                case "C+": return 2.3;
                case "C": return 2.0;
                case "C-": return 1.7;
                case "D": return 1.0;
                default: return 0.0;
            }
        }
    }

    private void exportGrades() {
        try {
            StringBuilder content = new StringBuilder();
            content.append("成绩单\n\n");
            content.append("学生信息：\n");
            content.append("姓名：").append(studentService.getStudentByUserId(currentUser.getId()).getName()).append("\n");
            content.append("学号：").append(studentService.getStudentByUserId(currentUser.getId()).getStudentId()).append("\n");
            content.append("学期：").append(semesterComboBox.getSelectedItem()).append("\n\n");
            content.append("课程成绩：\n");
            content.append(String.format("%-12s %-20s %-10s %-6s %-6s %-6s %-12s\n",
                "课程代码", "课程名称", "教师", "学分", "成绩", "绩点", "学期"));
            content.append("=".repeat(80)).append("\n");

            for (int i = 0; i < tableModel.getRowCount(); i++) {
                content.append(String.format("%-12s %-20s %-10s %-6s %-6s %-6s %-12s\n",
                    tableModel.getValueAt(i, 0),
                    tableModel.getValueAt(i, 1),
                    tableModel.getValueAt(i, 2),
                    tableModel.getValueAt(i, 3),
                    tableModel.getValueAt(i, 4),
                    tableModel.getValueAt(i, 5),
                    tableModel.getValueAt(i, 6)));
            }
            
            content.append("\n").append(gpaLabel.getText());

            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setDialogTitle("保存成绩单");
            fileChooser.setSelectedFile(new java.io.File("成绩单.txt"));
            
            if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
                java.io.File file = fileChooser.getSelectedFile();
                java.nio.file.Files.writeString(file.toPath(), content.toString());
                JOptionPane.showMessageDialog(this, "成绩单已成功导出！", "提示", JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "导出成绩单失败：" + e.getMessage(),
                "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
} 